package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());

        return addressMapper.selectList(wrapper);
    }

    @Override
    public void saveAddress(Address address) {
        // 补齐参数
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//设置非默认地址

        // 保存
        addressMapper.insert(address);
    }

    @Override
    public void setDefault(Long id) {
        //1 将房前用户的所有地址设置成非默认的0 也就是改为不是默认地址
            //设置更新字段
        Address address = new Address();
        address.setIsDefault(0);//设置非默认地址

            //设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());

            //开始更新
        addressMapper.update(address,wrapper);

        //2 将当前id设置问默认地址
        address.setIsDefault(1);
        address.setId(id);
        addressMapper.updateById(address);


    }

    @Override
    public Address findDefault() {
        //查询当前用户是不是默认地址的记录 is_default=1 的记录
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId())
                .eq(Address::getIsDefault,1);//默认地址


        return addressMapper.selectOne(wrapper);
    }

    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);

        return address;
    }
    //修改地址
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void delete(Long ids) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getId,ids);
        addressMapper.delete(wrapper);
    }
}
